interface CustomEvent extends Event {
  arguments: any[]
}

const bindHistoryEvent = (historyType: string) => {
  const historyEvent = history[historyType]
  return function (this: History, ...args: any[]) {
    const newEvent = historyEvent.apply(this, args) // 执行history函数
    const e = new Event(historyType) //声明自定义事件
    ;(e as CustomEvent).arguments = args
    window.dispatchEvent(e) // 抛出事件
    return newEvent // 返回方法，用于重写history的方法
  }
}

const rewriteMethod = () => {
  // 重写history原有的方法：
  history.pushState = bindHistoryEvent('pushState')
  history.replaceState = bindHistoryEvent('replaceState')
}

rewriteMethod()

export { bindHistoryEvent }
